package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.dtos.Result;
import com.heima.common.exception.AppHttpCodeEnum;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.admin.pojos.AdUser;
import com.heima.utils.common.BCrypt;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.RsaUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author heima
 * @since 2021-08-05
 */
@Service
@Transactional
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Value("${leadnews.jwt.privateKeyPath}")
    private String privateKeyPath;
    @Value("${leadnews.jwt.expire}")
    private Integer exprire;

    @Override
    public Result<Map<String, Object>> login(AdUser user) {
        String name = user.getName();
        String password = user.getPassword();
        if (!(StringUtils.isNotEmpty(name) && (StringUtils.isNotBlank(password)))) {
            throw new LeadNewsException(AppHttpCodeEnum.PARAM_INVALID);
        }

        QueryWrapper<AdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        AdUser loginUser = getOne(queryWrapper);
        if (loginUser == null) {
            throw new LeadNewsException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
//        密码是否正确
        if (!BCrypt.checkpw(password, loginUser.getPassword())) {
            throw new LeadNewsException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        loginUser.setPassword(null);

        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);
            String token = JwtUtils.generateTokenExpireInMinutes(loginUser, privateKey, exprire);

            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("user", loginUser);
            return Result.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadNewsException(AppHttpCodeEnum.TOKEN_INVALID);
        }
    }
}
